/**
 * Created by hooshim on 2014-12-04.
 */

var G_grid01 = "";
var G_grid02 = "";
var G_page = 1;

$(document).ready(function() {
    fnGetSubMenus();
    fnSetCurMenu(6);
    //fnGetLeftMenus('5');
    $("#_curMenu p").html("매출관리");

    $("#incomeDt").datepicker(G_calendar);
    $("#bankDt").datepicker(G_calendar);
    $("#actionDt").datepicker(G_calendar);

    var bodyWidth = $('body').innerWidth();
    bodyWidth = parseInt(bodyWidth,10) - 170;
    $('#_bodyRight').css('width', bodyWidth + 'px');
    var gSubMenus = fnGetSubMenus();
    var gScreenHeight = parseInt($(window).height(),10) - 120;
    //$("#_bodyLeft").css("height",gScreenHeight);
    $("#_bodyAll").css("height",gScreenHeight-58);
    gScreenHeight = parseInt(gScreenHeight,10) - 140;

    fnSetGrid01(gScreenHeight);
    fnSetGrid02();
    fnGetList01(1);
});

var fnSetGrid01 = function(h) {

    var grdCd = "grid01";

    var widths = [70, 120, 60, 80, 80, 80, 50, 80, 50, 150, 120];
    var titles = ['등록일', '거래처', 'INV/TAX', '금액', '원금', '부가세', '입금일', '입금액', '통장일', '내역', 'B/L'];
    var styles = ['text-align:center;', 'text-align:left;', 'text-align:center;', 'text-align:right;','text-align:right;', 'text-align:right;', 'text-align:center;', 'text-align:right;color:#0000CC;', 'text-align:center;', 'text-align:left;', 'text-align:center;'];

    var gInfo = new Object();
    gInfo["grdCd"] = "grid01";
    gInfo["title"] = "매출관리";
    gInfo["widths"] = widths;
    gInfo["titles"] = titles;
    gInfo["styles"] = styles;
    gInfo["function"] = "fnShowIncome";
    gInfo["fullWidth"] = "660";
    gInfo["fullHeight"] = h;
    gInfo["fix"] = "2";

    G_grid01 = JSON.stringify(gInfo);

    fnMkGridInit(G_grid01);
}

var fnSetGrid02 = function() {

    var grdCd = "grid02";

    var widths = [102, 75, 75, 75];
    var titles = ['거래처', '금액', '미수', '입금총액'];
    var styles = ['text-align:left;', 'text-align:right;','text-align:right;color:#CC0000;','text-align:right;color:#0000CC;'];

    var gInfo = new Object();
    gInfo["grdCd"] = grdCd;
    gInfo["title"] = "거래처별 매출";
    gInfo["widths"] = widths;
    gInfo["titles"] = titles;
    gInfo["styles"] = styles;
    //gInfo["function"] = "fnShowIncome";
    gInfo["fullWidth"] = "286";
    gInfo["fullHeight"] = "280";
    gInfo["fix"] = "1";

    G_grid02 = JSON.stringify(gInfo);

    fnMkGridInit(G_grid02);
}

var fnGetList = function() {

    if(event.keyCode != "13")
    {
        return; // 엔터일때만 수행
    }
    fnGetList01(1);
}

var fnGetList01 = function(page) {
    fnMkGridLoad(G_grid01);
    if (page) G_page = page;
    else page = G_page;
    var param  = "findCompany="+$("#findComapny").val();
    var valUrl = "./action/income/list.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            fnMkGrid(G_grid01,data);
            var sum = data.SUM.TBLINCOME[0];
            var sumAmt = sum.SUMAMT;
            var sumOrgAmt = sum.SUMORGAMT;
            var sumTax = sum.SUMTAX;
            var sumIncAmt = sum.SUMINCAMT;
            $("#sumAmt p").html(sumAmt + ' <span>|</span>');
            $("#sumOrgAmt p").html(sumOrgAmt + ' <span>|</span>');
            $("#sumTax p").html(sumTax + ' <span>|</span>');
            $("#sumIncAmt p").html(sumIncAmt + ' <span>|</span>');
            /*
             $("#table_body").html(list);
             $("#total_rows").html(data.TOTAL_ROW_COUNT);
             var paging = fnPaging('fnGetList', data.TOTAL_ROW_COUNT, page, 10);
             var pages = paging['prev'] + paging['pager'] + paging['next'];
             // alert(pages);
             $("#pager").html(pages);
             */

             fnGetList02(1);
        },
        error: function(data){
            alert('Error!!');
            alert(data.responseText);
        }
    });
}

var fnGetList02 = function(page) {
    fnMkGridLoad(G_grid02);
    if (page) G_page = page;
    else page = G_page;
    var param  = "findCompany="+$("#findComapny").val();
    var valUrl = "./action/income/listCompanySum.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){

            fnMkGrid(G_grid02,data);
            /*
             $("#table_body").html(list);
             $("#total_rows").html(data.TOTAL_ROW_COUNT);
             var paging = fnPaging('fnGetList', data.TOTAL_ROW_COUNT, page, 10);
             var pages = paging['prev'] + paging['pager'] + paging['next'];
             // alert(pages);
             $("#pager").html(pages);
             */
        },
        error: function(data){
            alert('Error!!');
            alert(data.responseText);
        }
    });
}

var fnShowIncome = function(incCds) {
    var divIncCd = incCds.split("^");
    var param  = "incCd="+divIncCd[0];
    param  += "&incSeq="+divIncCd[1];
    var valUrl = "./action/income/view.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            fnReset();

            var dataIncome = data.TBLINCOME[0];

            $("#incCd").val(dataIncome.INCCD);
            $("#billCd").val(dataIncome.BILLCD);
            $("#invoiceCd").val(dataIncome.INVOICECD);
            $("#invoiceMemo").val(dataIncome.INVOICEMEMO);
            $("#income").val(dataIncome.INCOME);
            $("#incomeDt").val(dataIncome.INCOMEDT);
            $("#amount").val(dataIncome.AMOUNT);
            $("#orgAmount").val(dataIncome.ORGAMOUNT);
            $("#tax").val(dataIncome.TAX);
            $("#memo").val(dataIncome.MEMO);
            $("#flag").val(dataIncome.FLAG);
            if (data.INCRESULT != undefined) {
                var dataIncResult = data.INCRESULT.TBLINCRESULT[0];
                $("#incAmount").val(dataIncResult.INCAMOUNT);
                $("#actionDt").val(dataIncResult.ACTIONDT);
                $("#bankDt").val(dataIncResult.BANKDT);
                $("#incSeq").val(dataIncResult.INCSEQ);
                $("#incMemo").val(dataIncResult.INCMEMO);
                $("#incFlag").val(dataIncResult.INCFLAG);
            }
            setTimeout("fnComboCompany('','"+dataIncome.COMPCD+"','compCd','skip');",500);
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

var fnSave = function() {
    if (!$("#income").val()) {
        alert("내역을 바르게 입력해 주세요.");
        $("#income").focus();
        return;
    }
    if (!$("#amount").val()) {
        alert("금액을 바르게 입력해 주세요.");
        $("#amount").focus();
        return;
    }

    var param = "incCd=" + $("#incCd").val();
    param += "&billCd=" + $("#billCd").val();
    param += "&invoiceCd=" + $("#invoiceCd").val();
    param += "&invoiceMemo=" + $("#invoiceMemo").val();
    param += "&incomeDt=" + $("#incomeDt").val();
    param += "&income=" + $("#income").val();
    param += "&amount=" + $("#amount").val().split(',').join('');
    param += "&orgAmount=" + $("#orgAmount").val().split(',').join('');
    param += "&tax=" + $("#tax").val().split(',').join('');
    param += "&compCd=" + $("#compCd").val();
    param += "&memo=" + $("#memo").val();
    param += "&flag=" + $("#flag").val();
    param += "&incSeq=" + $("#incSeq").val();
    param += "&incAmount=" + $("#incAmount").val().split(',').join('');
    param += "&actionDt=" + $("#actionDt").val();
    param += "&bankDt=" + $("#bankDt").val();
    param += "&incMemo=" + $("#incMemo").val();
    param += "&incFlag=" + $("#incFlag").val();

    var valUrl = "./action/income/save.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            if (data.rsStatus == "Success") {
                alert(data.rsStr);
                fnReset();
                fnGetList01();
                fnGetList02();
            }
            else {
                alert("저장 실패");
            }
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });
}

var fnReset = function() {
    $("#incCd").val('');
    $("#billCd").val('');
    $("#invoiceCd").val('');
    $("#invoiceMemo").val('');
    //$("#incomeDt").val('');
    $("#income").val('');
    $("#amount").val('');
    $("#orgAmount").val('');
    $("#tax").val('');
    $("#compNm").val('');
    $("#compCd").val('');
    $("#memo").val('');
    $("#flag").val('Y');

    fnAddIncome();
}

var fnAddIncome = function() {
    $("#incAmount").val('');
    //$("#actionDt").val('');
    //$("#bankDt").val('');
    $("#incSeq").val('');
    $("#incMemo").val('');
    $("#incFlag").val('Y');
}

var fnSetIncResult = function(m) {
    if (m == "all") {
        $("#incAmount").val($("#amount").val());
        $("#bankDt").val($("#incomeDt").val());
        $("#actionDt").val($("#incomeDt").val());
    }
    else
    {
        $("#incAmount").val($("#amount").val());
    }
}

//## Invoice 작성
var fnMkInvoice = function() {
    var checks = G_rowChecks.split('//').join('^');
    var divCheck = checks.split('^');
    var incCds = "";
    for (k=0; k<divCheck.length; k++)
    {
        var rowNum = divCheck[k].split('/').join('');
        if (rowNum.substr(0,6) == 'grid01')
        {
            var divDash = rowNum.split("-");
            var divCd = $("#grid01fix"+divDash[1]).attr("cd").split("^");
            if (incCds) incCds += ",";
            incCds += divCd[0];
        }
    }
    if (!incCds) {
        alert('매입건을 체크해 주세요');
        return;
    }
    if (!confirm('청구서를 작성하시겠습니까?'))
    {
        return;
    }
    var param = "incCds="+incCds
    var valUrl = "./action/income/saveInvoice.php";

    $.ajax({
        url: valUrl,
        type: 'POST',
        dataType: 'json',
        data: param,
        success: function(data){
            if (data.rsStatus == "Success") {
                alert(data.rsStr);
                fnReset();
                fnGetList01();
                fnGetList02();
            }
            else {
                alert("저장 실패");
            }
        },
        error: function(request,status,error){
            alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
        }
    });

}